package com.swak.zookeeper;

import java.util.Set;

import com.swak.Constants;
import com.swak.utils.ConcurrentHashSet;

/**
 * 
 * @author DELL
 */
public abstract class AbstractZookeeperService implements ZookeeperService {

	private final Set<String> persistentExistNodePath = new ConcurrentHashSet<>();

	@Override
	public void create(String path, boolean ephemeral) {
		if (!ephemeral) {
			if (this.persistentExistNodePath.contains(path)) {
				return;
			}
			if (this.checkExists(path)) {
				this.persistentExistNodePath.add(path);
				return;
			}
		}

		int i = path.lastIndexOf(Constants.PATH_SEPARATE);
		if (i > 0) {
			create(path.substring(0, i), false);
		}

		if (ephemeral) {
			createEphemeral(path);
		} else {
			createPersistent(path);
			persistentExistNodePath.add(path);
		}
	}

	@Override
	public void create(String path, String content, boolean ephemeral) {
		if (!ephemeral) {
			if (this.persistentExistNodePath.contains(path)) {
				return;
			}
			if (this.checkExists(path)) {
				this.persistentExistNodePath.add(path);
				return;
			}
		}

		int i = path.lastIndexOf(Constants.PATH_SEPARATE);
		if (i > 0) {
			create(path.substring(0, i), false);
		}

		if (ephemeral) {
			createEphemeral(path, content);
		} else {
			createPersistent(path, content);
			persistentExistNodePath.add(path);
		}
	}

	@Override
	public void delete(String path) {
		persistentExistNodePath.remove(path);
		this.deletePath(path);
	}

	protected abstract void createEphemeral(String path, String content);

	protected abstract void createPersistent(String path);

	protected abstract void createEphemeral(String path);

	protected abstract void createPersistent(String path, String content);

	protected abstract void deletePath(String path);
}
